<script setup>
import { ElMessage } from 'element-plus'
import { ref, watch } from 'vue'

import {
  addMagnetFace,
  updateMagnetFace,
} from '@/api/manager/dataManage/deviceManage.js'
import VUpload from '@/components/upload/index.vue'
import { useDict } from '@/hooks/useDict'

defineOptions({
  name: 'PersonAdd',
})

const props = defineProps({
  gateId: {
    type: String,
    required: true,
  },
  detail: {
    type: Object,
    default: () => {},
  },
  parkList: {
    type: Array,
    default: () => [],
  },
})

const emit = defineEmits(['close'])

const { dict } = useDict(['gender'])

const formRef = ref()

const dialogVisible = ref(false)

const title = ref('')

const type = ref('add')

const currentDetail = ref({})

const files = ref([])

const formRules = ref({
  employeeNo: [
    {
      message: '工号不能为空',
      required: true,
      trigger: ['blur', 'change'],
    },
  ],
  name: [
    {
      message: '姓名不能为空',
      required: true,
      trigger: ['blur', 'change'],
    },
  ],
  timeDuration: [
    {
      message: '有效期不能为空',
      required: true,
      trigger: ['blur', 'change'],
    },
  ],
  imgId: [
    {
      message: '照片不能为空',
      required: true,
      trigger: ['blur', 'change'],
    },
  ],
})

const handleCancel = () => {
  handleClose()
}

const handleSave = () => {
  formRef.value?.validate((valid) => {
    if (valid) {
      const params = {
        pedestrianIds: [props.gateId],
        employeeNo: currentDetail.value.employeeNo,
        name: currentDetail.value.name,
        gender: currentDetail.value.gender,
        imgId: currentDetail.value.imgId,
      }
      if (
        currentDetail.value.timeDuration &&
        currentDetail.value.timeDuration.length === 2
      ) {
        params.beginTime = currentDetail.value.timeDuration[0]
        params.endTime = currentDetail.value.timeDuration[1]
      } else {
        params.startTime = ''
        params.endTime = ''
      }
      if (type.value === 'add') {
        addMagnetFace(params)
          .then((res) => {
            if (res.success) {
              ElMessage.success('新增成功')
              handleClose(true)
            } else {
              console.error('新增失败', res)
              ElMessage.error(res.message || '新增失败')
            }
          })
          .catch((err) => {
            console.error('新增失败', err)
          })
      } else {
        updateMagnetFace(params)
          .then((res) => {
            if (res.success) {
              ElMessage.success('编辑成功')
              handleClose(true)
            } else {
              console.error('编辑失败', res)
              ElMessage.error(res.message || '编辑失败')
            }
          })
          .catch((err) => {
            console.error('编辑失败', err)
          })
      }
    }
  })
}

const handleClose = (shouldRefresh) => {
  dialogVisible.value = false
  formRef.value?.resetFields()
  files.value = []
  emit('close', shouldRefresh)
}

watch(
  () => props.detail,
  (val) => {
    if (val) {
      if (val.Valid?.beginTime && val.Valid?.endTime) {
        val.timeDuration = [
          val.Valid.beginTime.replace('T', ' '),
          val.Valid.endTime.replace('T', ' '),
        ]
      }
      currentDetail.value = val
    }
  },
  {
    immediate: true,
  },
)

watch(
  () => dialogVisible.value,
  (val) => {
    if (!val) {
      formRef.value?.resetFields()
    }
  },
)

watch(
  () => files.value,
  (val) => {
    if (val.length) {
      if (val[0].pkid) {
        currentDetail.value.imgId = val[0].pkid
      } else {
        currentDetail.value.imgId = ''
      }
    } else {
      currentDetail.value.imgId = ''
    }
  },
)

defineExpose({ dialogVisible, title, type })
</script>

<template>
  <el-dialog
    class="custom-dialog"
    v-model="dialogVisible"
    :title="title"
    width="813px"
    @close="handleClose"
  >
    <div class="custom-detail">
      <el-form
        ref="formRef"
        :model="currentDetail"
        :rules="formRules"
        label-position="right"
        label-width="100"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="工号：" prop="employeeNo">
              <el-input
                v-model="currentDetail.employeeNo"
                :disabled="type !== 'add'"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名：" prop="name">
              <el-input v-model="currentDetail.name" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="有效期：" prop="timeDuration">
              <el-date-picker
                v-model="currentDetail.timeDuration"
                type="datetimerange"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别：" prop="gender">
              <el-select v-model="currentDetail.gender" placeholder="请选择">
                <el-option
                  v-for="item in dict['gender']"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-if="type === 'add'" :span="12">
            <el-form-item label="照片：" prop="imgId">
              <VUpload
                v-model="files"
                :limit="1"
                accept=".png, .jpg, .jpeg"
                list-type="picture-card"
                upload-text="上传照片"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <template #footer>
      <el-row style="width: 100%" justify="end" align="middle">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </el-row>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.el-form-item {
  width: 100%;
  margin-bottom: 0;
}
</style>
